<?php
/**
 * VIP会员API逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\api\logic;

use app\common\logic\Vip as CommonVip;

class Vip extends ApiBase
{
    
    public static $commonVipLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonVipLogic) && static::$commonVipLogic = new CommonVip();
    }

    /**
     * 获取VIP套餐列表
     */
    public function getVipPackages($data = [])
    {
        $result = static::$commonVipLogic->getVipPackages($data);
        
        return $result[0] == RESULT_SUCCESS ? $result[2] : [];
    }
    
    /**
     * 获取用户VIP信息
     */
    public function getUserVipInfo($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonVipLogic->getUserVipInfo($data);
        
        return $result;
    }
    
    /**
     * 创建VIP订单
     */
    public function createVipOrder($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonVipLogic->createVipOrder($data);
        if (is_array($result) && isset($result[0]) && $result[0] === RESULT_SUCCESS && isset($result[2]) && is_array($result[2])) {
            $orderInfo = $result[2];
            $user = $this->modelUser->getInfo(['id' => $data['user_id']], 'openid');
            if ($user && !empty($user['openid'])) {
                $driverOrder = [
                    'order_sn' => $orderInfo['order_no'] ?? '',
                    'body' => $orderInfo['package_name'] ?? 'VIP会员购买',
                    'order_amount' => floatval($orderInfo['price'] ?? 0),
                    'openid' => $user['openid']
                ];
                try {
                    $params = $this->servicePay->driverWxpay->getJsApiParamsRaw($driverOrder);
                    $result[2]['payment_params'] = $params;
                } catch (\Exception $e) {
                }
            }
        }
        return $result;
    }
    
    /**
     * 支付成功回调
     */
    public function paymentSuccess($data = [])
    {
        $result = static::$commonVipLogic->paymentSuccess($data);
        
        return $result;
    }
    
    /**
     * 获取最近充值会员列表
     */
    public function getRecentVipUsers($data = [])
    {
        $result = static::$commonVipLogic->getRecentVipUsers($data);
        
        return $result;
    }
    
    /**
     * 检查用户VIP状态
     */
    public function checkUserVip($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        $result = static::$commonVipLogic->checkUserVip($data);
        
        return $result;
    }
    
    /**
     * 获取用户VIP历史记录
     * @author 王勇程 <laughskydragon@qq.com>
     * @param array $data
     * @return array
     */
    public function getUserVipHistory($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        // 2. 调用getWhere方法
        $where = static::$commonVipLogic->getWhere($data);

        // 3. 调用common层业务逻辑
        $result = static::$commonVipLogic->getUserVipHistory($where);

        return $result;
    }

    /**
     * 请求支付参数（微信JSAPI）
     */
    public function requestPayment($data = [])
    {
        try {
            $token = $data['user_token'] ?? '';
            if (!empty($token)) {
                $userData = get_user_by_token($token);
                $data['user_id'] = $userData['user_id'];
            }

            $orderId = $data['order_id'] ?? 0;
            $orderNo = $data['order_no'] ?? '';
            $userId = $data['user_id'] ?? 0;

            if (!$orderId && empty($orderNo)) {
                return [RESULT_ERROR, '订单参数不能为空'];
            }

            $where = [];
            !empty($orderNo) && $where['order_no'] = $orderNo;
            !empty($orderId) && $where['id'] = $orderId;
            $order = $this->modelVipOrder->getInfo($where);
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            if ($userId && $order['user_id'] != $userId) {
                return [RESULT_ERROR, '订单归属异常'];
            }
            if (!empty($order['order_status']) && intval($order['order_status']) === 1) {
                return [RESULT_ERROR, '订单已支付'];
            }

            $user = $this->modelUser->getInfo(['id' => $order['user_id']], 'openid');
            if (!$user || empty($user['openid'])) {
                return [RESULT_ERROR, '缺少微信openid'];
            }

            $driverOrder = [
                'order_sn' => $order['order_no'],
                'body' => $order['package_name'] ?: 'VIP会员购买',
                'order_amount' => floatval($order['amount']),
                'openid' => $user['openid']
            ];

            $params = $this->servicePay->driverWxpay->getJsApiParamsRaw($driverOrder);
            if (empty($params) || !is_array($params)) {
                return [RESULT_ERROR, '获取支付参数失败'];
            }

            return [RESULT_SUCCESS, '获取成功', ['payment_params' => $params]];
        } catch (\Exception $e) {
            return [RESULT_ERROR, '请求支付异常：' . $e->getMessage()];
        }
    }

    /**
     * 微信支付异步通知
     */
    public function wechatNotify()
    {
        try {
            $orderNo = get_order_sn();
            if (empty($orderNo)) {
                return [RESULT_ERROR, '订单号解析失败'];
            }

            $vipOrder = $this->modelVipOrder->getInfo(['order_no' => $orderNo]);
            if (!$vipOrder) {
                return [RESULT_ERROR, '订单不存在'];
            }
            if (!empty($vipOrder['order_status']) && intval($vipOrder['order_status']) === 1) {
                return [RESULT_SUCCESS, '已支付'];
            }

            $data = $this->servicePay->driverWxpay->notify();
            if (!$data) {
                return [RESULT_ERROR, '通知验签失败'];
            }

            $transactionId = $data['transaction_id'] ?? '';
            return $this->paymentSuccess(['order_no' => $orderNo, 'transaction_id' => $transactionId]);
        } catch (\Exception $e) {
            return [RESULT_ERROR, '通知处理异常：' . $e->getMessage()];
        }
    }
}
